package com.nativetalk.common.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by Peter on 2017/6/23.
 */
public class DateUtil {

    public static String format(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static String format(Date date, String format, String clientTimeZoneId) {
        if (StringUtils.isNotBlank(clientTimeZoneId)) {
            TimeZone clientTimeZone = TimeZone.getTimeZone(clientTimeZoneId);
            return DateFormatUtils.format(date, format, clientTimeZone);
        } else {
            return format(date, format);
        }

    }

    public static String format(Timestamp timestamp, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d = new Date(timestamp.getTime());
        return sdf.format(d);
    }

    /**
     * 计算两个时间之间的距离（秒）
     *
     * @param start
     * @param end
     * @return
     */
    public static long distanceSecond(Date start, Date end) {
        long startSecond = start.getTime() / 1000;
        long endSecond = end.getTime() / 1000;
        return endSecond - startSecond;
    }


    /**
     * 计算两个时间之间的距离（秒）
     *
     * @param start
     * @param end
     * @return
     */
    public static long distanceMinute(Date start, Date end) {
        long startSecond = start.getTime() / 1000;
        long endSecond = end.getTime() / 1000;
        return (endSecond - startSecond) / 60;
    }

    /**
     * 对给定的时间添加一个分钟数，如果minute是负数就是减去minute分钟
     *
     * @param start_time
     * @param minute
     * @return
     */
    public static Date addMinute(Timestamp start_time, int minute) {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date(start_time.getTime()));
        c.add(Calendar.MINUTE, minute);
        return c.getTime();
    }
}
